﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1300"
        destroy-on-close
        :close-on-click-modal="false"
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >

            <el-row>
               
                <el-col :span="6">
                    <el-form-item label-width="120px" label="申请单位：">
                        {{entityObj.storeName}}
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="申请人：">
                        {{entityObj.createName}}
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="退货时间：">
                        <el-date-picker
                            v-model="entityObj.afterOrderTime"
                            type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder="请输入退货时间"
                            style="width: 100%;margin-left: 9px;"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="供货单位:" prop="purchaseUnityId">
                        <!-- <sc-purchase-unity-select
                            :queryType='"store/current-purchaseUnity"'
                            placeholder="---请选择采购单位---"
                            ref="purchaseUnitySelect"
                            :props="purchaseUnityProps"
                            :selectKeyValue="'purchaseUnityId'"
                            v-model="entityObj.purchaseUnitys"
                            @fatherMethod="purchaseUnitySelectProcess"
                            :multiple="false"
                        ></sc-purchase-unity-select> -->
                        <el-select @change="changepurchaseUnity" class="w-300" placeholder="---请输入供货单位名称---" v-model="entityObj.purchaseUnityId">
                            <el-option v-for="item in optionsPurchaseUnity" :key="item.purchaseUnityId"
                                :label="item.purchaseUnityName" :value="item.purchaseUnityId" />
					    </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
              
            </el-row>
            <!-- <el-row>
                <el-col :span="6">
                    <el-form-item label-width="120px" label="供应商：" prop="supplierId">
                        <sc-supplier-select
                            ref="supplierSelect"
                            :props="supplierProps"
                            :selectKeyValue="'supplierId'"
                            :multiple="false"
                            v-model="entityObj.suppliers"
                            @fatherMethod="supplierSelectProcess"
                        ></sc-supplier-select>
                    </el-form-item>
                </el-col>
            </el-row> -->
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="退换货清单" prop="afterOrderItems">
                        <!-- <el-button type="primary" size="small" @click="opTaskChoice()" >从收货单选择</el-button> -->
                        <el-button type="primary" size="small" @click="opMaterialChoice()" >选择物资</el-button>
                        
                    </el-form-item>
                </el-col>
               
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="">
                        <el-table :data="entityObj.afterOrderItems" border style="width: 100%;" show-summary :summary-method="getSummaries" :row-class-name="tableRowClassName">
                            <el-table-column label="状态" width="100">
                                    <template #default="scope"> {{scope.row.statusDesc}} </template>
                            </el-table-column>
                            <el-table-column label="物料编码" width="100">
                                    <template #default="scope"> {{scope.row.materialCode}} </template> 
                            </el-table-column>
         
                            <el-table-column label="物料名称" width="180">
                                <template #default="scope">
                                    <div v-if="scope.row.applyOrderId>0 && scope.row.price<=0">
                                        {{scope.row.materialName}}   <el-tag type="danger" effect="light">赠</el-tag>
                                    </div>
                                    <div v-else>
                                        <div style="color: #318cf2; cursor: pointer;" @click="handlePreview(scope.row)">
                                            {{scope.row.materialName}}
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="分类" width="150">
                                <template #default="scope">{{scope.row.materialTypeName}}</template>
                            </el-table-column>
                            <el-table-column label="规格" width="120">
                                <template #default="scope">{{scope.row.materialSpecs}}</template>
                            </el-table-column>
                            <el-table-column label="单位" width="150">
                                <template #default="scope">
                                    <el-select
                                        placeholder="请选择单位"
                                        v-model="scope.row.newUnitCode"
                                        style="width: 100%"
                                        filterable  allow-create
                                        @change="selectChange(scope.row)" 
                                        @blur="selectBlur($event,scope.row)"
                                    >
                                        <el-option
                                            v-for="item in optionsUnit"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            
                            <!-- <el-table-column label="单价" width="70" >
                                <template #default="scope">
                                   
                                    <div v-if="scope.row.applyOrderId>0">
                                        {{scope.row.price}}
                                    </div>
                                  
                                    <div v-else>
                                        <span v-if="scope.row.price>0">{{scope.row.price}}</span>
                                        <span v-else>--</span>
                                    </div>
                                    
                                </template>
                            </el-table-column> -->
                           
                            <el-table-column label="要货编号" width="150">
                                <template #default="scope">
                                    <span v-if="scope.row.applyOrderCode==''">无</span>
                                    <span v-else>{{scope.row.applyOrderCode}}</span>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="供货单位" width="150">
                                <template #default="scope">
                                    <span v-if="scope.row.supplierName==''">无</span>
                                    <span v-else>{{scope.row.supplierName}}</span>
                                </template>
                            </el-table-column> -->
                            <el-table-column label="破损处理" width="130" prop="afterOrderType">
                                <template #default="scope">
                                    <!-- || isGift(scope.row) -->
                                    <el-select placeholder="处理方式" v-model="scope.row.afterOrderType" style="width: 100px" :disabled="isReadonly(scope.row) ">
                                        <el-option label="补发" :value="0"/>
                                        <el-option label="退货" :value="1"/>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="申请数量" width="130" prop="qty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.qty"
                                        style="width: 100%"
                                        :step="1"
                                        :max="scope.row.taskQty"
                                        :min="1"
                                        controls-position="right"
                                        :disabled="isReadonly(scope.row)"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                           
                            <!-- <el-table-column label="实际接单数量" width="120" v-if="choiceType==2">
                                <template #default="scope">
                                    <span v-if="scope.row.receiveQty>0">{{scope.row.receiveQty}}</span>
                                    <span v-else>/</span>
                                </template>
                            </el-table-column> -->
                            <el-table-column label="应退金额" width="100" v-if="choiceType==2">
                                <template #default="scope">
                                    <span v-if="scope.row.afterOrderType==0">--</span>
                                    <span v-if="scope.row.afterOrderType==1">{{scope.row.price * (scope.row.receiveQty?scope.row.receiveQty:scope.row.qty)}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="破损照片" width="150" >
                                <template #default="scope">
                                        <sc-upload-multiple 
                                            v-model="scope.row.images"
                                            :objName="'Supply/AfterOrder'" 
                                            :uploadType="'OSS'" 
                                            :bucketName="'jtmc'" 
                                            :limit="5"
                                            
                                            :disabled="isReadonly(scope.row)"
                                             />
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" width="150" >
                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" :disabled="isReadonly(scope.row)"/>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <el-button
                                        type="danger"
                                        size="small"
                                        @click="deleteRow(scope.$index, scope.row)"
                                        :disabled="isReadonly(scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                    
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="备注">
                        <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'Show'" type="warning"  :loading="isSaveing"  @click="opStag()">暂 存</el-button>
            <el-button v-if="mode != 'Show'" type="primary"  :loading="isSaveing"  @click="submit()">提交申请</el-button>
        </template>
        <template>
            <el-dialog
                v-model="materialVisible"
                title="选择物料"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row>
                    <sc-material-choice
                        ref="scMaterialChoice"
                        :queryType="'delivery-protocol/material-pages'"
                        :queryList="applyOrderQueryList"
                    ></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialVisible = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
            <el-dialog
                v-model="taskMaterialVisible"
                title="选择收货订单物料"
                :width="1300"
                :center="true"
                append-to-body
                style="height: 480px"
            >
                <el-row>
                    <sc-task-order-item-choice
                        ref="scTaskOrderItemChoice"
                        :defaultQueryList="defaultQueryList"
                    ></sc-task-order-item-choice>
                </el-row>
                <template #footer>
                    <el-button @click="taskMaterialVisible = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setTaskOrderItemChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>

        <!-- 预览组件 -->
        <el-image-viewer v-if="showImage" @close="closeViewer" :url-list="srcList" />


    </full-screen-dialog>
</template>

<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "补发/退货申请",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                afterOrderTime:"",
                remarks:"",
                afterOrderItems:[],

            },
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                purchaseUnitys: [
                    { required: true, type: "object", message: "请填写供货单位" },
                ],
                afterOrderItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                        trigger: "change",
                    },
                    
                ], 
                afterOrderType: [
                    { required: true, type: "number", message: "请填写破损类型" },
                ],
                qty: [
                    { required: true, type: "number", message: "请填写申请数量" },
                ],
                purchaseUnityId: [
                    { required: true, type: "number", message: "请填写供货单位" },
                ],
            },
            choiceType:2,//选择类型
           //物料中选择
            materialVisible: false,
            applyOrderQueryList:{},
            defaultQueryList:{},
            //收货单中选择
            taskMaterialVisible: false,
            supplierProps: {
                label: "supplierName",
                value: "supplierId",
            },
            purchaseUnityId:0,//采购单位ID
            purchaseUnityName:"",//采购单位名称
            purchaseUnityProps: {
                label: "purchaseUnityName",
                value: "purchaseUnityId",
            },
            optionsPurchaseUnity:[],
            optionsUnit: [],
             //预览图片
             previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
        };
    },
   
    watch: {
            // 'entityObj.afterOrderItems':{
            //     handler(newvalue, oldVal) {
            //         let returnFee = 0;
            //         if(newvalue)
            //         {
            //             newvalue.map((p) => {
            //                 returnFee += p.afterOrderType==1?p.price * p.qty:0;
            //             });
            //             this.entityObj.totalReturnFee=returnFee;
            //         }
            //     },
            //     deep: true
            // }
	},
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            
            return this;
        },
        //从物料中选择
        opMaterialChoice() {
            if (!this.entityObj.storeId) {
                this.$message.error("请先选择要货单位");
                return;
            }

            if (!this.entityObj.purchaseUnityId) {
                this.$message.error("请先选择供货单位");
                return;
            }
            this.choiceType=1;
            this.materialVisible = true;
            this.applyOrderQueryList = { storeId: this.entityObj.storeId,purchaseUnityId:this.entityObj.purchaseUnityId };
            this.$nextTick(() => {
                this.$refs.scMaterialChoice.opBindData();
            });
        },
        //从收货单选择
        opTaskChoice() {
            if (!this.entityObj.storeId) {
                this.$message.error("请先选择要货单位");
                return;
            }

            if (!this.entityObj.purchaseUnityId) {
                this.$message.error("请先选择供货单位");
                return;
            }

            this.defaultQueryList = { storeId: this.entityObj.storeId,purchaseUnityId:this.entityObj.purchaseUnityId };
            this.choiceType=2;
            this.taskMaterialVisible = true;
            this.$nextTick(() => {
                this.$refs.scTaskOrderItemChoice.opBindData();
            });
        },
         //从物料中选择后
         setMaterialChoice() {
            var that=this;
            if (this.choiceType==1) {
                console.log("供货单位",that.purchaseUnityName);
                console.log("物资选择",this.$refs.scMaterialChoice.selectionRows);
                this.$refs.scMaterialChoice.selectionRows.forEach((row) => {
                    row.purchaseUnityId=that.purchaseUnityId;
                    row.supplierName=that.purchaseUnityName;
                    row.qty=1;
                    row.afterOrderType=1;
                    row.applyOrderCode='';
                    row.price=row.materialItems[0].price;
                    row.statusDesc="";
                    row.newUnitCode=row.unitCode;
                    row.newUnitName=row.unitName;
                });
			}
            this.entityObj.afterOrderItems.push(...this.$refs.scMaterialChoice.selectionRows);
            this.materialVisible = false;

        },
        //从收货单选择后
        setTaskOrderItemChoice() {
            this.entityObj.afterOrderItems.push(...this.$refs.scTaskOrderItemChoice.selectionRows);
            console.log("收货选择",this.entityObj.afterOrderItems);
            this.taskMaterialVisible = false;
        },
        async supplierSelectProcess(rowData) {
            this.entityObj.supplierId=rowData.supplierId
        },
        
        deleteRow(index) {
            this.entityObj.afterOrderItems.splice(index, 1);
        },
        summaryFun(val){
            const { columns, row } = val;
            const sums = [];

            columns.forEach((item, index) => {
                if (index === 0) {
                    var totalAmount=0;
                    this.entityObj.afterOrderItems.forEach((item) => {
                        totalAmount+=item.price * (item.receiveQty)?item.receiveQty:item.qty
                    });
                    console.log("totalAmount",totalAmount);
                     sums[index] = '总计：'+totalAmount;
                    return;
                }
            });
            return sums;
        },
        getSummaries(param){
            const{ columns,data}=param;
            const sums=[];
            columns.forEach((column,index)=>{
                if (index === 0) {
                    sums[index] = '合计'
                    return;
                }
                const values=data.map(item=>Number(item[column.property]));
               
                if(column.property=='qty'){
                    if(!values.every(item=>isNaN(item))){
                        const total = values.reduce((a, b) => a + b, 0)
                        sums[index] = total
                    }
                }
            });
            return sums;
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                console.log("验证结果",valid);
                if (valid) {
                    this.isSaveing = true;
                    const data={ ...this.entityObj}
                    try {
                        var returnValue =await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"? "after-order/create": "after-order/update",data);
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        tableRowClassName({row,index}){
            if(row.status==6)
            {
                return "info-row"              
            }
        },
        //是否只读
        isReadonly(row){
            if(row.status==6)
            {
                return true;              
            }
            return false;
        },
        isGift(row)
        {
            //赠送
            if(row.price==0)
            {
                row.afterOrderType=0;
                return true;              
            }
        },
        //暂存
        async opStag(){
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;

                    this.entityObj.isStag=1;
  
                    const data={ ...this.entityObj}
                    console.log("暂存",data);
                    try {
                        var returnValue =await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"? "after-order/create": "after-order/update",data);
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            console.log(" data",data);
            this.entityObj.afterOrderCode= data.afterOrderCode;
            this.entityObj.afterOrderId=data.afterOrderId;
            this.entityObj.createName = data.createName;
            this.entityObj.storeId = data.storeId;
            this.entityObj.storeName = data.storeName;
            this.entityObj.afterOrderTime = data.afterOrderTime;
            this.entityObj.purchaseUnityId=data.purchaseUnityId;
            this.entityObj.purchaseUnitys={purchaseUnityId:data.purchaseUnityId,purchaseUnityName:data.purchaseUnityName}
            this.choiceType=data.applyOrderId==0?1:2;

            this.getDetail(data.afterOrderId);
            
        },
        async initOptions() {
            try {
				const returnStatus = await this.$API.auth.GetProcessApi.get(
					"store/current-purchaseUnity"
				);
				if (returnStatus.status == 200) {
					this.optionsPurchaseUnity = returnStatus.response;
					this.formData.pId = this.optionsPurchaseUnity[0].purchaseUnityId;
				} else {
					this.$message.error("操作失败:" + returnStatus.msg);
				}
			} catch (error) {  }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/dic-options",
                    { ParentBaseDictionaryCodes: ["002"] }
                );
                if (returnValue.status == 200) {

                    this.optionsUnit = returnValue.response.find(
                        (p) => p.code == "002"
                    ).optionsDetails;
                    console.log("单位",this.optionsUnit);
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //获取明细
        async getDetail(afterOrderId)
        {
            if (afterOrderId) {
                try {
                    
                    
                    var returnValue=await this.$API.auth.GetProcessApi.get(
                        `after-order/${afterOrderId}`,
                        { }
                    );
                    if (returnValue.status == 200) {
                           console.log("Detail",returnValue.response);
                            this.entityObj.afterOrderItems = returnValue.response;
                            if(returnValue.response.length!=null && returnValue.response.length>=0)
                            {

                                this.entityObj.remarks = returnValue.response[0].afterRemarks;
                                console.log("Detail",this.entityObj.remarks);
                            }
                           
                       } else {
                           this.$message.error("操作失败:" + returnValue.msg);
                       }
                   

                    
                   
                } catch (error) {
                    this.loading = false;
                    return false;
                }
            }
        },
        async purchaseUnitySelectProcess(rowData) {
            console.log(rowData)
            if (rowData) {
                this.purchaseUnityId=rowData.purchaseUnityId;
                this.purchaseUnityName=rowData.purchaseUnityName;
                this.entityObj.purchaseUnityId = rowData.purchaseUnityId;
                this.entityObj.purchaseUnityName = rowData.purchaseUnityName;
                this.entityObj.purchaseUnitys={purchaseUnityId:rowData.purchaseUnityId,purchaseUnityName:rowData.purchaseUnityName}
            }
        },
         // 单位手动输入
         selectBlur(e,row) {
            if (e.target.value) {
                
                var obj=this.optionsUnit.filter(p=>p.label==e.target.value)[0];
                if(obj)
                {
                    row.price=0;
                    row.newUnitCode=obj.value;
                    row.newUnitName=obj.label;
                    console.log("手动输入",row);
                    
                }else
                {
                    row.price=0;
                    row.newUnitCode=e.target.value;
                    row.newUnitName=e.target.value;
                    console.log("手动输入1",row);
                }
               
            }
        },
        //单位变化
        selectChange(row) {
           var obj=this.optionsUnit.filter(p=>p.value==row.newUnitCode)[0];
           if(obj)
           {
              row.price=0;
              row.newUnitName=obj.label;
              console.log("单位变化",row);
           }
           
        },
         //图片预览
         handlePreview(row) {
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image

        },
        closeViewer(){
            this.showImage = false; 
        },
    },
    async mounted() {
        await this.initOptions();
        
        if(this.mode=='Add'){
           
            this.entityObj.createName = tool.data.get("USER_INFO").Name;
            this.entityObj.storeId = tool.data.get("USER_INFO").OrgId;
            this.entityObj.storeName = tool.data.get("USER_INFO").OrgName;
            this.entityObj.afterOrderTime = tool.formatDate(new Date());

            try {
                await this.$API.auth.GetProcessApi.get(
                    `store/${this.entityObj.storeId}/purchaseUnity`,
                    { }
                ).then((res)=>{
                    if (res.status == 200) {
                        this.purchaseUnityId =res.response.purchaseUnityId;
                        this.purchaseUnityName =res.response.purchaseUnityName;
                        this.entityObj.purchaseUnityId = res.response.purchaseUnityId;
                        console.log("采购单位名称",this.purchaseUnityName );
                    } 
                });
                
            } catch (error) {
                return false;
            }
        }
        
    },
};
</script>
<style scoped>

/deep/ .el-upload--picture-card{ 
    width: 50px;
    height: 50px;
}
/deep/ .el-upload{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail{
    width: 50px;
    height: 50px;
    line-height: 50px; 
}
/deep/ .el-table .info-row > td 
{
    background:#e4e7ed;
    user-select: none; /* 禁用文本选择 */
    pointer-events: none; /* 禁用鼠标事件 */


}
</style>
